import { useState, useEffect, useCallback } from 'react';

/**
 * API请求Hook - 管理API调用状态
 * @param {Function} apiFunction - API调用函数
 * @param {any} initialData - 初始数据
 * @param {boolean} immediate - 是否立即执行
 * @returns {object} API状态和控制函数
 */
export const useApi = (apiFunction, initialData = null, immediate = true) => {
    const [data, setData] = useState(initialData);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const execute = useCallback(async (...params) => {
        try {
            setLoading(true);
            setError(null);
            const response = await apiFunction(...params);
            setData(response);
            return response;
        } catch (err) {
            setError(err);
            throw err;
        } finally {
            setLoading(false);
        }
    }, [apiFunction]);

    useEffect(() => {
        if (immediate && apiFunction) {
            execute();
        }
    }, [execute, immediate]);

    const reset = useCallback(() => {
        setData(initialData);
        setError(null);
        setLoading(false);
    }, [initialData]);

    return {
        data,
        loading,
        error,
        execute,
        reset
    };
};

/**
 * 列表API Hook - 管理带分页的列表数据
 * @param {Function} apiFunction - API调用函数
 * @param {object} initialParams - 初始参数
 * @returns {object} 列表状态和控制函数
 */
export const useApiList = (apiFunction, initialParams = {}) => {
    const [data, setData] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [params, setParams] = useState(initialParams);

    const fetchData = useCallback(async (newParams = {}) => {
        try {
            setLoading(true);
            setError(null);
            const mergedParams = { ...params, ...newParams };
            const response = await apiFunction(mergedParams);

            // 适配不同的响应格式
            if (response.data) {
                setData(response.data.list || response.data);
                setTotal(response.data.total || response.data.length || 0);
            } else {
                setData(response);
                setTotal(response.length || 0);
            }

            setParams(mergedParams);
            return response;
        } catch (err) {
            setError(err);
            setData([]);
            setTotal(0);
            throw err;
        } finally {
            setLoading(false);
        }
    }, [apiFunction, params]);

    // 初次加载
    useEffect(() => {
        fetchData();
    }, []);

    // 刷新数据
    const refresh = useCallback(() => {
        return fetchData(params);
    }, [fetchData, params]);

    // 搜索
    const search = useCallback((searchParams) => {
        return fetchData({ ...params, ...searchParams, current: 1 });
    }, [fetchData, params]);

    // 分页
    const changePage = useCallback((current, pageSize) => {
        return fetchData({ ...params, current, pageSize });
    }, [fetchData, params]);

    return {
        data,
        total,
        loading,
        error,
        params,
        refresh,
        search,
        changePage,
        fetchData
    };
};
